<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\AuthenticationException;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class CheckToken
{
    /**
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     * @throws AuthenticationException
     */
    public function handle($request, Closure $next)
    {
        try {

            if (! $user = JWTAuth::parseToken()->authenticate()) {  //获取到用户数据，并赋值给$user
                dd(JWTAuth::getPayload()->get('sub'));

//                throw new AuthenticationException();
            }
            //如果想向控制器里传入用户信息，将数据添加到$request里面
            $request->attributes->add($user);//添加参数
            return $next($request);

        } catch (TokenExpiredException $e) {

//            return response()->json([
//                'errcode' => 1003,
//                'errmsg' => 'token 过期' , //token已过期
//            ]);
            throw new AuthenticationException("token 过期",1003);

        } catch (TokenInvalidException $e) {

//            return response()->json([
//                'errcode' => 1002,
//                'errmsg' => 'token 无效',  //token无效
//            ]);
            throw new AuthenticationException("token 过期",1002);
        } catch (JWTException $e) {

//            return response()->json([
//                'errcode' => 1001,
//                'errmsg' => '缺少token' , //token为空
//            ]);
            throw new AuthenticationException("缺少token",1001);
        }


    }
}
